import path from 'node:path'
import process from 'node:process'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import autoImport from 'unplugin-auto-import/vite'
import components from 'unplugin-vue-components/vite'
import {loadEnv, type PluginOption} from 'vite'
import {compression} from 'vite-plugin-compression2'
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'
import VueDevTools from 'vite-plugin-vue-devtools'
import {LayuiVueResolver} from '@layui/unplugin-vue-components/resolvers'

export default function createVitePlugins(mode: string, isBuild = false) {
    const viteEnv = loadEnv(mode, process.cwd())

    const vitePlugins: (PluginOption | PluginOption[])[] = [

        // https://github.com/unplugin/unplugin-auto-import
        autoImport({
            imports: [
                'vue',
                'vue-router',
                'pinia',
            ],
            resolvers: [
                LayuiVueResolver(),
            ],
            dts: './src/types/auto-imports.d.ts',
        }),

        // https://github.com/unplugin/unplugin-vue-components
        components({
            dirs: ['src/components'],
            include: [/\.vue$/, /\.vue\?vue/, /\.tsx$/],
            resolvers: [
                LayuiVueResolver({
                    resolveIcons: true,
                    exclude: ['LightIcon', 'DarkIcon']
                }),
            ],
            dts: './src/types/components.d.ts',
        }),

        vue(),
        vueJsx(),

        // https://github.com/vuejs/devtools-next
        viteEnv.VITE_OPEN_DEVTOOLS === 'true' && VueDevTools(),




        // https://github.com/vbenjs/vite-plugin-svg-icons
        createSvgIconsPlugin({
            iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/')],
            symbolId: 'svg-[dir]-[name]',
            svgoOptions: isBuild,
        }),


        // https://github.com/nonzzz/vite-plugin-compression
        viteEnv.VITE_BUILD_COMPRESS?.split(',').includes('gzip') && compression(),
        viteEnv.VITE_BUILD_COMPRESS?.split(',').includes('brotli') && compression({
            exclude: [/\.(br)$/, /\.(gz)$/],
            algorithm: 'brotliCompress',
        }),
    ]
    return vitePlugins
}
